/* ****路由处理函数**** */
const fs = require('fs');
let sessions = {}

function home(req, res) {

    var string = fs.readFileSync('../website/index.html', 'utf8');
    //let cookies = request.headers.cookie.split(';')
    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    let cookies = ''
    if (req.headers.cookie) {
        cookies = req.headers.cookie.split('; ')
    }
    // console.log(cookies);
    let hash = {}
    for (let i = 0; i < cookies.length; i++) {
        let parts = cookies[i].split('=')
        let key = parts[0]
        let value = parts[1]
        hash[key] = value
    }
    let mySession = sessions[hash.sessionId]
    let email
    if (mySession) {
        email = mySession.sign_in_email
    }
    let users = fs.readFileSync('./db/users', 'utf8')
    users = JSON.parse(users)
    let foundUser = false
    for (let i = 0; i < users.length; i++) {
        if (users[i].email === email) {
            console.log(users[i]);
            foundUser = users[i];
        }
    }
    if (foundUser) {
        string = string.replace('href="http://127.0.0.1:3000/login"', '')
        string = string.replace('登录', foundUser.email)
        string = string.replace('href="http://127.0.0.1:3000/reg"', 'href="http://127.0.0.1:3000/logout"')
        string = string.replace('注册', '登出')

    } else {
        // string = string.replace('__password__', '不知道')
    }
    res.write(string)
    res.end()
    // req.url = "/index.html";
    // handleAsFile(req, res, req.url)
}

function reg(req, res, qstr) {
    console.log(qstr);
    let strings = qstr.split('&');
    let hash = {}
    strings.forEach((string) => {
        let parts = string.split('=')
        let key = parts[0]
        let value = parts[1]
        hash[key] = decodeURIComponent(value); //url里面不能有@符号，如果有就会转成%40
    })
    console.log(hash)
    let {
        email,
        password,
        password_confirmation
    } = hash
    if (email.indexOf('@') === -1) {
        console.log(111);
        res.setHeader('Content-Type', 'application/json;charset=utf-8')
        res.statusCode = 400
        //当邮箱错误的时候给页面一个json格式的响应
        res.write(`{
        "errors": {
          "email": "invalid"
        }
      }`)
    } else if (password !== password_confirmation) {
        res.statusCode = 400
        res.write('password is error')
    } else {
        //将文件users里面的内容赋值给users变量
        var users = fs.readFileSync('./db/users', 'utf8')
        try {
            users = JSON.parse(users)
        } catch (exception) {
            users = []
        }
        //设置一个中间变量inUse 解决users重复问题
        let inUse = false;
        //遍历
        for (let i = 0; i < users.length; i++) {
            //如果users里面其中有一项的email等于你传入的email
            if (users[i].email === email) {
                //就让inUse=true
                inUse = true;
                //然后退出循环
                break;
            }
        }
        //如果inUse是true响应一个400请求
        if (inUse) {
            res.statusCode = 400
            res.write('email is exist')
        } else {
            users.push({
                email: email,
                password: password
            })
            res.setHeader('Set-Cookie', `sign_in_email=${email}`)
            var usersString = JSON.stringify(users)
            fs.writeFileSync('./db/users', usersString);
            res.statusCode = 200
        }
    }

    res.end()

}
// 登录
function login(req, res, qstr) {

    let strings = qstr.split('&')
    let hash = {}
    strings.forEach((string) => {
        let parts = string.split('=')
        let key = parts[0]
        let value = parts[1]
        hash[key] = decodeURIComponent(value)
    })
    let {
        email,
        password
    } = hash
    var users = fs.readFileSync('./db/users', 'utf8');
    users = JSON.parse(users)
    let found
    for (let i = 0; i < users.length; i++) {
        if (users[i].email === email && users[i].password === password) {
            found = true
            break
        }
    }
    if (found) {
        let sessionId = Math.random() * 10000000
        sessions[sessionId] = {
            sign_in_email: email
        }
        res.setHeader('Set-Cookie', `sessionId=${sessionId}`)
        res.statusCode = 200;
    } else {
        res.statusCode = 401
    }
    res.end()

}

function logout(req, res) {
    var string = fs.readFileSync('../website/index.html', 'utf8');
    res.writeHead(200, {
        'Content-Type': 'text/html; charset=utf-8',
        //删除客户端的sessionid，关键是Max-Age=0
        'Set-Cookie': 'sessionId=0;Max-Age=0'
    });
    console.log('已退出');
    res.write(string)
    res.end()
    
}
module.exports = {
    login,
    reg,
    home,
    logout
}